/*
 * @Author: hongbin
 * @Date: 2022-11-03 12:59:51
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-20 21:23:15
 * @Description:添加用户
 */
import { NextApiRequest, NextApiResponse } from "next";
import { VerifyFields } from "../../../src/api/utils";
import DB from "../mongodb";
import { receiveRequest } from "../utils";

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
    if (!receiveRequest(req, res, "POST")) return;
    const db = await DB;
    console.log(req.body);

    if (!VerifyFields.has(req.body, ["name", "password"])) {
        return res.status(500).json("缺少关键字段");
    }
    const userInfo = { ...req.body };
    // 查询数据库中数据
    const user = await db.collection("userInfo").find({ name: userInfo.name, password: userInfo.password }).toArray();
    console.log(user);
    if (user.length) {
        res.status(200).json({ data: user[0] });
        return;
    }
    res.json({ data: { msg: "未找得到用户" }, code: -1 });
}

/*

async function insertOne(collection, data) {
    return await mongoClient.collection(collection).insertOne(data)
        .then((res) => res)
        .catch((err) => { console.log("insertOne fail:", err) });
}
async function aggregate({ collection, pipeline }) {
    return await mongoClient.collection(collection).aggregate(pipeline).toArray()
    // .then((res) => res)
    // .catch((err) => { console.log("aggregate fail:", err) });
}
//cusFilter 覆盖 _id 以满足普通 _id查找不足的情况  cusData同样
async function updateOne({ collection, _id, cusFilter, data, cusData }) {
    return await mongoClient.collection(collection).updateOne(cusFilter || { _id: ObjectId(_id) }, cusData || { $set: data })
        .then((res) => res)
        .catch((err) => { console.log("updateOne fail:", err) });
}

async function deleteOne(collection, _id) {
    return await mongoClient.collection(collection).deleteOne({ _id: ObjectId(_id) })
        .then((res) => res)
        .catch((err) => { console.log("deleteOne fail:", err) });
}

const findData = async ({ collection, find = {}, project = {}, sort = {}, limit = 20, skip = 0 }) =>
    await mongoClient.collection(collection)
        .find(find).project(project).sort(sort).limit(limit).skip(skip).toArray();

const getCollectionCounts = async ({ collection, find = {} }) => await mongoClient.collection(collection).countDocuments(find);


*/
